package com.ruoyi.fun.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.fun.domain.EcUserBrowseHistory;
import com.ruoyi.fun.domain.EcProduct;
import com.ruoyi.fun.service.IEcUserBrowseHistoryService;
import com.ruoyi.fun.service.IEcProductService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 移动端用户浏览历史Controller（无需权限验证）
 * 
 * @author ruoyi
 * @date 2025-01-16
 */
@Anonymous
@RestController
@RequestMapping("/mobile/browseHistory")
public class EcMobileBrowseHistoryController extends BaseController
{
    @Autowired
    private IEcUserBrowseHistoryService ecUserBrowseHistoryService;
    
    @Autowired
    private IEcProductService ecProductService;

    /**
     * 根据用户ID查询浏览历史列表（我的足迹）
     */
    @GetMapping("/user/{userId}")
    public TableDataInfo getUserBrowseHistory(@PathVariable Long userId, Long orgId)
    {
        startPage();
        // 使用前端传递的组织ID，如果没有则使用默认值103
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        List<EcUserBrowseHistory> list = ecUserBrowseHistoryService.selectEcUserBrowseHistoryByUserIdAndOrgId(userId, orgId);
        
        // 根据productId获取最新的商品信息并更新浏览历史记录
        for (EcUserBrowseHistory history : list) {
            if (history.getProductId() != null) {
                // 使用orgId过滤查询商品信息
                EcProduct product = ecProductService.selectEcProductByProductIdAndOrgId(history.getProductId(), orgId);
                if (product != null) {
                    // 更新商品名称和图片信息
                    history.setProductName(product.getProductName());
                    history.setProductImage(product.getMainImage());
                    history.setProductPrice(product.getPrice());
                }
            }
        }
        
        return getDataTable(list);
    }

    /**
     * 获取用户浏览历史详细信息
     */
    @GetMapping("/{browseId}")
    public AjaxResult getInfo(@PathVariable Long browseId)
    {
        return success(ecUserBrowseHistoryService.selectEcUserBrowseHistoryByBrowseId(browseId));
    }

    /**
     * 新增用户浏览历史记录
     */
    @PostMapping
    public AjaxResult add(@RequestBody EcUserBrowseHistory ecUserBrowseHistory)
    {
        // 使用前端传递的组织ID，如果没有则使用默认值103
        Long orgId = ecUserBrowseHistory.getOrgId();
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        ecUserBrowseHistory.setOrgId(orgId);
        int result = ecUserBrowseHistoryService.insertEcUserBrowseHistory(ecUserBrowseHistory);
        if (result > 0) {
            // 返回新创建记录的ID
            return AjaxResult.success("新增成功", ecUserBrowseHistory.getBrowseId());
        }
        return AjaxResult.error("新增失败");
    }

    /**
     * 更新用户浏览历史记录（用于分段更新浏览时长）
     */
    @PutMapping
    public AjaxResult update(@RequestBody EcUserBrowseHistory ecUserBrowseHistory)
    {
        return toAjax(ecUserBrowseHistoryService.updateEcUserBrowseHistory(ecUserBrowseHistory));
    }

    /**
     * 根据用户ID和商品ID更新或创建浏览记录
     */
    @PostMapping("/upsert")
    public AjaxResult upsertBrowseHistory(@RequestBody EcUserBrowseHistory ecUserBrowseHistory)
    {
        // 使用前端传递的组织ID，如果没有则使用默认值103
        Long orgId = ecUserBrowseHistory.getOrgId();
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        // 查询用户当天对该商品的浏览记录（使用orgId过滤）
        EcUserBrowseHistory todayRecord = ecUserBrowseHistoryService.selectTodayBrowseHistoryByOrgId(
            ecUserBrowseHistory.getUserId(), ecUserBrowseHistory.getProductId(), orgId);
        
        if (todayRecord != null) {
            // 如果当天已有浏览记录，累加浏览时长
            Integer currentDuration = todayRecord.getBrowseDuration() != null ? todayRecord.getBrowseDuration() : 0;
            Integer newDuration = ecUserBrowseHistory.getBrowseDuration() != null ? ecUserBrowseHistory.getBrowseDuration() : 0;
            todayRecord.setBrowseDuration(currentDuration + newDuration);
            todayRecord.setBrowseTime(ecUserBrowseHistory.getBrowseTime()); // 更新最后浏览时间
            
            int result = ecUserBrowseHistoryService.updateEcUserBrowseHistory(todayRecord);
            return result > 0 ? AjaxResult.success("更新成功", todayRecord.getBrowseId()) : AjaxResult.error("更新失败");
        } else {
            // 当天没有浏览记录，创建新记录
            ecUserBrowseHistory.setOrgId(orgId);
            int result = ecUserBrowseHistoryService.insertEcUserBrowseHistory(ecUserBrowseHistory);
            return result > 0 ? AjaxResult.success("新增成功", ecUserBrowseHistory.getBrowseId()) : AjaxResult.error("新增失败");
        }
    }

    /**
     * 查询用户今日对特定商品的浏览记录
     */
    @GetMapping("/today/{userId}/{productId}")
    public AjaxResult getTodayBrowseHistory(@PathVariable Long userId, @PathVariable Long productId, Long orgId)
    {
        // 使用前端传递的组织ID，如果没有则使用默认值103
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        EcUserBrowseHistory todayRecord = ecUserBrowseHistoryService.selectTodayBrowseHistoryByOrgId(userId, productId, orgId);
        return success(todayRecord);
    }

    /**
     * 根据用户ID查询浏览历史列表（不分页）
     */
    @GetMapping("/list/{userId}")
    public AjaxResult getBrowseHistoryList(@PathVariable Long userId, Long orgId)
    {
        // 使用前端传递的组织ID，如果没有则使用默认值103
        if (orgId == null) {
            orgId = 103L;
        }
        List<EcUserBrowseHistory> list = ecUserBrowseHistoryService.selectEcUserBrowseHistoryByUserIdAndOrgId(userId, orgId);
        
        // 根据productId获取最新的商品信息并更新浏览历史记录
        for (EcUserBrowseHistory history : list) {
            if (history.getProductId() != null) {
                // 使用orgId过滤查询商品信息
                EcProduct product = ecProductService.selectEcProductByProductIdAndOrgId(history.getProductId(), orgId);
                if (product != null) {
                    // 更新商品名称和图片信息
                    history.setProductName(product.getProductName());
                    history.setProductImage(product.getMainImage());
                    history.setProductPrice(product.getPrice());
                }
            }
        }
        
        return success(list);
    }
    /**
     * 根据id和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:ecmobilebrowsehistory:query')")
    @GetMapping(value = "/{id}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("id") Long id, @PathVariable("orgId") Long orgId)
    {
        return success(ecUserBrowseHistoryService.selectEcUserBrowseHistoryByBrowseIdAndOrgId(id, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('system:ecmobilebrowsehistory:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcUserBrowseHistory ecUserBrowseHistory = new EcUserBrowseHistory();
        List<EcUserBrowseHistory> list = ecUserBrowseHistoryService.selectEcUserBrowseHistoryListByOrgId(ecUserBrowseHistory, orgId);
        return getDataTable(list);
    }


}